<template>
  <div class="templateDetail">
    <div class="tips">
      操作说明
      <a-tooltip placement="right">
        <template #title>
          <span>
            当前正在设置栏目手机端的适用模型，模板关联模型后可在【栏目管理-栏目手机端模板】中勾选此模板
          </span>
        </template>
        <span class="iconfont icon-hint1"></span>
      </a-tooltip>
    </div>
    <div class="templateDetailTop">
      <div>
        <div>
          <span>模板名称：</span>
          <span>{{ route.query.name }}</span>
        </div>
        <a-form
          name="advanced_search"
          autoComplete="off"
          class="ant-advanced-search-form"
          :model="formState"
          ref="columnFrom"
          v-if="modelType == 1 || modelType == 2"
        >
          <a-form-item
            label="适用模型"
            name="modelIdList"
            :rules="[
              { required: true, trigger: 'change', message: '请选择适用模型!' },
            ]"
          >
            <a-select
              class="modal-select"
              v-model:value="formState.modelIdList"
              @change="checked_Keys"
              :fieldNames="fieldNames"
              :max-tag-count="3"
              mode="multiple"
              placeholder="请选择"
              :options="treeData"
            ></a-select>
          </a-form-item>
        </a-form>
      </div>
      <a-button
        class="addButton"
        type="primary"
        @click="addRecord"
        v-if="modelType == 1 || modelType == 2"
      >
        保存
      </a-button>
    </div>

    <a-textarea
      class="templateDetailContent"
      type="textarea"
      readonly
      v-model:value="content"
      placeholder="请输入模板html"
    ></a-textarea>
    <!-- <pre style="white-space: pre-wrap">{{ content }}</pre> -->
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { useRoute } from "vue-router";
import type { TreeProps } from "ant-design-vue";
import { Modal, message } from "ant-design-vue";
import { scrollType, dataSourceType, configDataType } from "@/type";
import getters from "@/store/getters";
import request from "@/api/index";
import { useRouter } from "vue-router";

//interface
interface Options {
  [propName: string | number]: any;
}
//树结构数据
const fieldNames = reactive<dataSourceType>({
  label: "name",
  value: "id",
});
const formState = ref<dataSourceType>({
  modelIdList: [],
});
const treeData = ref<Options[]>([]);
const userInfo = getters.userInfo();
const columnFrom = ref<any>("columnFrom");
const route: any = useRoute();
const modelType = ref<number>();
const detailsData = ref({});
const content = ref<string>("");
const modelIdList = ref<(string | number)[]>([]);
const router = useRouter();
const checked_Keys = (data: any) => {
  formState.value.modelIdList = data;
};
const buttonMessage = async (msg: dataSourceType) => {
  columnFrom.value
    .validate()
    .then(() => {})
    .catch(() => {});
};
const emits = defineEmits(["handleCancle"]);
const handleCancle = (e: MouseEvent) => {
  emits("handleCancle", e);
};
//获取新增层级树列表
const fetchResourceGroupTreeList = async () => {
  let params = {
    allPermFilter: true,
    siteId: userInfo.siteId,
  };
  treeData.value = await request.fetchResourceGroupTreeList(params);
  // dataList.push(...treeData.value);
};
// 查看详情
const fetchTemplateDetail = async () => {
  let data = await request.fetchTemplateDetail({
    relativePath: route.query.val,
  });
  detailsData.value = data;
  content.value = data.content;
  content.value = content.value
    .replace(/"<!/g, "<!")
    .replace('</html>"', "</html>")
    .replace(/(\\n\\t)/g, "\n\t")
    .replace(/(\\n)/g, "\n")
    .replace(/\s+\n/g, "\n")
    .replace(/\s+\r\n/g, "\r\n")
    .replace(/\\"/g, '"');
  formState.value.modelIdList = data.modelIdList || [];
};
// 保存
const addRecord = async () => {
  request
    .fetchTemplateBindingsModel({
      modelIdList: formState.value.modelIdList,
      relativePath: route.query.val,
    })
    .then((res: any) => {
      if (res.code == "00000 00000") {
        message.success(res.message);

        // router.push({
        //   path: "/config/templateManagement",
        // });
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};

// 模型下拉列表
const fetchModelModelList = async () => {
  treeData.value = await request.fetchModelModelList({
    modelType: modelType.value,
  });
};
//onmounted
onMounted(async () => {
  let reg = RegExp(/\/channel\//);
  let reg1 = RegExp(/\/content\//);
  console.log(route.query.val.includes("%5Cchannel%5C"),'route.query.val.includes("%5Cchannel%5C")');
  if (reg.test(route.query.val) || route.query.val.includes("channel")) {
    
    modelType.value = 1;
    fetchModelModelList();
  } else if (
    reg1.test(route.query.val) ||
    route.query.val.includes("content")
  ) {
    modelType.value = 2;
    fetchModelModelList();
  }

  fetchTemplateDetail();
});
</script>

<style lang="scss" scoped>
.templateDetail {
  width: 100%;
  height: 100%;
  padding: 24px;
  background-color: #fff;

  .tips {
    margin-bottom: 24px;
    font-size: 14px;
    color: #333;
  }

  .templateDetailTop {
    width: 100%;

    background-color: #f0f0f0;
    padding: 24px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    > div:first-child {
      display: flex;

      // margin-top: 20px;
      // align-items: center;
    }

    .ant-form {
      margin-left: 24px;
    }

    .ant-form-item {
      margin-bottom: 0;
    }

    .ant-select {
      width: 500px;
    }

    .addButton {
      float: right;
    }
  }

  .templateDetailContent {
    padding: 8px 24px;
    margin-top: 24px;
    width: 100%;
    height: calc(100% - 190px);
    border: 1px solid #f0f0f0;
    border-radius: 4px;
    overflow: auto;
    white-space: pre-wrap;

    .right-form {
      height: 100%;
      overflow-y: scroll;
    }
  }
}
</style>
